const Adminuser = require('../../modules/Adminuser')

module.exports = app =>{

const assert = require('http-assert') /* npm i assert */
const express = require('express') /* npm i express@next */
const jwt = require('jsonwebtoken') /* npm i jsonwebtoken */


const router = express.Router({
    mergeParams:true
})

router.post('/',async (req,res)=>{
    const model = await req.Model.create(req.body)
    res.send(model)
})

router.delete('/:id',async (req,res)=>{
    await req.Model.findByIdAndDelete(req.params.id,req.body)
    res.send({
        success:true
    })
})

router.get('/',async (req,res,next)=>{
    const token = String(req.headers.authorization || '').split(' ').pop()
    assert(token,401,'请先登录')
    const {id} = jwt.verify(token,app.get('secret'))
    assert(id,401,'请先登录')
    req.user = await Adminuser.findById(id)
    assert(req.user,401,'请先登录')
    await next()
},async (req,res)=>{
    const queryOptions = {}
    if (req.Model.modelName === 'Category'){
        queryOptions.populate = 'parent'
    }
    const model = await req.Model.find().setOptions(queryOptions).limit(100)
    res.send(model)
})

router.get('/:id',async (req,res)=>{
    const model = await req.Model.findById(req.params.id)
    res.send(model)
})

router.put('/:id',async (req,res)=>{
    const model = await req.Model.findByIdAndUpdate(req.params.id,req.body)
    res.send(model)
})

app.use('/admin/api/rest/:resource',async (req,res,next)=>{
    const modelName = require('inflection').classify(req.params.resource)
    req.Model = require(`../../modules/${modelName}`)
    next()
},router)

const multer = require('multer')
const upload = multer({
    dest:__dirname + '/../../uploads'
})
app.post('/admin/api/upload',upload.single('file'),async (req,res)=>{
    const file = req.file
    file.url = `http://localhost:3000/uploads/${file.filename}`
    res.send(file)
})

// 登陆界面的接口
app.post('/admin/api/login',async (req,res)=>{
    const {username,password} = req.body
    const admin = require('../../modules/Adminuser') 
    const user = await admin.findOne({username}).select('+password')
    assert(user,422,'用户不存在')
   /*  if(!user){
        return res.status(422).send({
        message:'用户不存在'
        })
    }
 */
    // 校验密码是否正确
    const istrue = require('bcrypt').compareSync(password,user.password)
    assert(istrue,422,'密码错误')
  /*   if(!istrue){
        return res.status(422).send({
            message:'密码错误'
        })
    } */

    // 返回token
    const token = jwt.sign({id:user._id},app.get('secret'))
    res.send({token})
})

app.use(async(err,req,res,next)=>{
    res.status(err.statusCode || 500).send({
        message:err.message
    })
})
}




